package com.gx.smart.building.ui.common.adapter;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.mylhyl.circledialog.CircleDialog;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.io.File;
import java.io.FileDescriptor;

/**
 * @author: xiaosy
 * 时间: 2022/3/31
 * @Description: java类作用描述
 * @Version: 1.0
 **/
public class UploadImageUtil {
    private final Context mContext;
    private final ActivityResultLauncher<Intent> photoLauncher;
    private final ActivityResultLauncher<Intent> cameraLauncher;

    public UploadImageUtil(Context context, ActivityResultLauncher<Intent> photoLauncher, ActivityResultLauncher<Intent> cameraLauncher) {
        this.mContext = context;
        this.photoLauncher = photoLauncher;
        this.cameraLauncher = cameraLauncher;
    }

    public interface UploadImageListener {
        void displayImage1(Uri uri);

        void displayFail();
        void deleteImage();
        void uploadTask1(String fileName, byte[] file);
    }

    public UploadImageListener listener;

    public void setListener(UploadImageListener listener) {
        this.listener = listener;
    }

    private final String[] items = {"选择本地照片", "拍照"};
    public Uri cameraUri = null;


    /**
     * 上传图片
     */
    public void uploadImage1() {
        new CircleDialog.Builder()
                .setItems(items, (parent, view, position, id) -> {
                    handleEvent1(position);
                    return true;
                })
                .setNegative("取消", null)
                .show(((AppCompatActivity) mContext).getSupportFragmentManager());
    }

    public void deleteImage1() {
        new CircleDialog.Builder()
                .setTitle("删除图片")
                .setWidth(0.8f)
                .setText("你确定要删除上传图片?")
                .setNegative("取消", null)
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(listener != null){
                            listener.deleteImage();
                        }
                    }
                })
                .show(((AppCompatActivity) mContext).getSupportFragmentManager());
    }

    /**
     * 跳转到相册
     */
    private void gotoPhoto1() {
        Logger.d("*****************打开图库********************");
        //跳转到调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        photoLauncher.launch(Intent.createChooser(intent, "请选择图片"));
    }

    /**
     * 跳转到照相机
     */
    private void gotoCamera1() {
        Logger.d("*****************打开相机********************");
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            Uri uri = createImageUri();
            cameraUri = uri;
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            //设置7.0中共享文件，分享路径定义在xml/file_paths.xml
            File tempFile = createFile();
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(((AppCompatActivity) mContext),
                    ((AppCompatActivity) mContext).getApplication().getPackageName() + ".fileProvider", tempFile);
            cameraUri = contentUri;
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            File tempFile = createFile();
            cameraUri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        }
        cameraLauncher.launch(intent);
    }


    private File createFile() {
        File storageDir = ((AppCompatActivity) mContext).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        return new File(storageDir, System.currentTimeMillis() + ".jpg");
    }


    public void handleEvent1(int position) {
        switch (position) {
            case 0: // 选择本地照片,跳转到相册
                //权限判断
                AndPermission.with(((AppCompatActivity) mContext))
                        .runtime()
                        .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                        .onGranted(permissions -> {
                            //跳转到相册
                            gotoPhoto1();
                        })
                        .onDenied(permissions -> {
                            ToastUtils.showLong("没有获取访问相册的权限");
                            if (AndPermission.hasAlwaysDeniedPermission(((AppCompatActivity) mContext), permissions)) {
                                new CircleDialog.Builder()
                                        .setTitle("系统权限设置")
                                        .setText("您确定要获取访问相册的权限吗？")
                                        .setPositive("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                            }
                                        })
                                        .setNegative("取消", null)
                                        .show(((AppCompatActivity) mContext).getSupportFragmentManager());
                            }
                        }).start();

                break;
            case 1: // 拍照,跳转到调用系统相机
                //权限判断
                AndPermission.with(((AppCompatActivity) mContext))
                        .runtime()
                        .permission(Permission.CAMERA)
                        .onGranted(permissions -> {
                            //跳转到调用系统相机
                            gotoCamera1();
                        })
                        .onDenied(permissions -> {
                            ToastUtils.showLong("没有获取访问相机的权限");
                            if (AndPermission.hasAlwaysDeniedPermission(((AppCompatActivity) mContext), permissions)) {
                                new CircleDialog.Builder()
                                        .setTitle("系统权限设置")
                                        .setText("您确定要获取访问相机的权限吗？")
                                        .setPositive("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                            }
                                        })
                                        .setNegative("取消", null)
                                        .show(((AppCompatActivity) mContext).getSupportFragmentManager());
                            }

                        }).start();
                break;
        }
    }


    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, System.currentTimeMillis() + ".jpg");
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        Uri uri;
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            uri = ((AppCompatActivity) mContext).getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    values
            );

        } else {
            uri = ((AppCompatActivity) mContext).getContentResolver().insert(
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                    values
            );
        }
        return uri;
    }


    // 通过uri加载图片
    private Bitmap getBitmapFromUri(Uri uri) {
        try {
            ParcelFileDescriptor parcelFileDescriptor =
                    ((AppCompatActivity) mContext).getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void uploadImage1(Uri uri) {
        String fileName = getFileNameByUri(uri);
        Logger.d("uploadImage fileName=" + fileName);
        Bitmap bitmap = getBitmapFromUri(uri);
        Logger.d("uploadImage bitmap : " + bitmap != null);
        Bitmap newBitmap = ImageUtils.compressBySampleSize(bitmap, 500, 500);
        Logger.d("newBitmap size:" + newBitmap.getByteCount());
        byte[] file = ImageUtils.bitmap2Bytes(newBitmap, Bitmap.CompressFormat.JPEG, 100);
        if (listener != null) {
            listener.uploadTask1(fileName, file);
        }
        Logger.d("uploadImage fileName=" + fileName);
    }


    public String getFileNameByUri(Uri uri) {
        String fileName = String.valueOf(System.currentTimeMillis());
        Cursor cursor = ((AppCompatActivity) mContext).getContentResolver().query(uri, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            fileName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME));
            cursor.close();
        }
        return fileName;
    }

    public class UploadImageAsyncTask1 extends AsyncTask<Uri, Void, Void> {


        @Override
        protected Void doInBackground(Uri... uris) {
            uploadImage1(uris[0]);
            return null;
        }
    }


}
